package com.itany.mall.dao.impl;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

import com.itany.mall.dao.ProductDao;
import com.itany.mall.entity.Product;
import com.itany.mall.exception.DataAccessException;
import com.itany.mall.factory.Component;

import database.Database02;

@Component
public class ProductDaoImpl implements ProductDao {

	@Override
	public List<Product> selectAll() {
		List<Product> list = new ArrayList<Product>();
		File dir = new File(Database02.PRODUCT_DIR);
		File[] fs = dir.listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(Database02.PRODUCT_SUFFIX);
			}
		});
		try {
			for (File f : fs) {
				ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
				Product t = (Product) ois.readObject();
				ois.close();
				list.add(t);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new DataAccessException(e);
		}
		return list;
	}

	@Override
	public Product selectByName(String name) {
		File dir = new File(Database02.PRODUCT_DIR);
		File[] fs = dir.listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(Database02.PRODUCT_SUFFIX);
			}
		});
		try {
			for (File f : fs) {
				ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
				Product t = (Product) ois.readObject();
				ois.close();
				if (t.getName().equalsIgnoreCase(name)) {
					return t;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new DataAccessException(e);
		}
		return null;
	}

	@Override
	public void insert(Product p) {
		try {
			p.setId(Database02.autoIncrement(Database02.PRODUCT_DIR));
			Database02.saveMallData(Database02.PRODUCT_DIR, p, Database02.PRODUCT_SUFFIX);
		} catch (IOException e) {
			e.printStackTrace();
			throw new DataAccessException(e);
		}

	}

	@Override
	public Product selectById(long productId) {
		File f = new File(Database02.PRODUCT_DIR, productId + Database02.PRODUCT_SUFFIX);
		if (!f.exists()) {
			return null;
		}

		try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
			Product p = (Product) ois.readObject();
			return p;
		} catch (Exception e) {
			e.printStackTrace();
			throw new DataAccessException(e);
		}
	}

}
